/**
 * 
 */
package fb.chatter.controller;

import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import fb.chatter.constant.Constant;
import fb.chatter.model.User;
import fb.chatter.utils.AccessTokenUtils;
import fb.chatter.utils.HttpConnectionUtils;
import fb.chatter.utils.JSONUtils;

/**
 * @author Horizon
 * 
 */
public class LoginFormController implements Initializable {

	/**
	 * The Login form
	 */
	private Stage stage = new Stage();

	/**
	 * The separation string.
	 */
	public static final String QUESTION_CODE_EQUAL = "?code=";
	
	/**
	 * The Form that call the FXMLLoader.load() funtion to load the LoginForm.
	 */
	private MainFormController parentForm;
	
	/**
	 * @param parentForm the parentForm to set
	 */
	public void setParentForm(MainFormController parentForm) {
		this.parentForm = parentForm;
	}

	/**
	 * The JavaFx components
	 */
	@FXML
	private WebView webView;

	@Override
	public void initialize(URL location, ResourceBundle resources) {

		VBox root = new VBox();
		final WebView browser = new WebView();
		browser.getEngine().load(Constant.AUTHORIZATION_URL);
		root.getChildren().addAll(browser);
		Scene scene = new Scene(root, 600, 400);

		final WebEngine webEngine = browser.getEngine();

		// Process for each successful navigation.
		webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {

			@SuppressWarnings("rawtypes")
			public void changed(ObservableValue ov, State oldState, State newState) {
				if (newState == State.SUCCEEDED) {
					String location = webEngine.getLocation();
					
					// TMPPPPPPPPPPPPPPPPPPPPPPPP
					buildCurrentUser();
					stage.close();
					parentForm.loadFriendListForm();

					// Code URL
					if (location.contains(QUESTION_CODE_EQUAL)) {

						Constant.ACCESS_TOKEN = AccessTokenUtils.getAccessTokenValue(location);
						if (Constant.ACCESS_TOKEN != null) {
							
							/**
							 * Authorize successfully. 
							 */
							// Build the current user
							buildCurrentUser();
							
							// Close LoginForm
							stage.close();
							
							// update UI
							parentForm.loadFriendListForm();
						}
					}
				}
			}
		});

		stage.getIcons().add(new Image("/logo-facebook.png"));
		stage.setTitle("Facebook Login form");
		stage.setScene(scene);
		stage.show();

		// TMP
//		parentForm.loadFriendListForm();
	}
	
	/**
	 * To build the current user: Constant.currentUser.
	 * This method is called when only user login successfully.
	 */
	private void buildCurrentUser(){
		
		String getCurrentUserUrl = "https://graph.facebook.com/me?access_token=" + Constant.ACCESS_TOKEN ;
		String currentUserJson = HttpConnectionUtils.doGetTextRequest(getCurrentUserUrl);
		Constant.currentUser = (User) JSONUtils.conveJSONToObject(currentUserJson, User.class);
		
		String friendProfilePictureURL = "http://graph.facebook.com/" + Constant.currentUser.getId() + "/picture?width=100&height=100";
		InputStream profilePictureStream = HttpConnectionUtils.doGetInputStreamRequest(friendProfilePictureURL);
		Constant.currentUser.setPicture(new Image(profilePictureStream));
	}
}
